package com.jason.project.CloseScreen;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

public class MainActivity extends Activity {
	static final int REQUEST_DEVICE_ADMIN = 1;

	DevicePolicyManager mDPM = null;
	ComponentName mDeviceAdminSample = null;
	CheckBox mChkDeviceAdmin = null;

	private void giveUpAdminActive() {
		mDPM.removeActiveAdmin(mDeviceAdminSample);
		updateChkDeviceAdminStatus();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_DEVICE_ADMIN:
			updateChkDeviceAdminStatus();
			return;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void onChkDeviceAdminClick(View v) {
		boolean bActive = mChkDeviceAdmin.isChecked();
		if (bActive) {
			requestAdminActive();
		} else {
			giveUpAdminActive();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
		mDeviceAdminSample = new ComponentName(this, DeviceAdmin.class);

		mChkDeviceAdmin = (CheckBox) findViewById(R.id.chkDeviceAdmin);

		updateChkDeviceAdminStatus();
	}

	private void requestAdminActive() {
		Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
		intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
				mDeviceAdminSample);
		intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
				R.string.desc_request_device_admin);
		startActivityForResult(intent, REQUEST_DEVICE_ADMIN);
	}

	private void updateChkDeviceAdminStatus() {
		boolean bActive = mDPM.isAdminActive(mDeviceAdminSample);
		mChkDeviceAdmin.setChecked(bActive);
	}
}
